#ifndef CUTDATAMODEL_H
#define CUTDATAMODEL_H

#include <QObject>
#include <QVector>
#include <QVariant>
#include <QAbstractListModel>
#include <QFile>
#include <QTextStream>
#include <QStandardPaths>
#include <QCoreApplication> // 新增：用于获取程序目录
#include <QDir>
#include <QDebug>

#include "Mid_Struct.h"

class CutDataModel : public QAbstractListModel
{
    Q_OBJECT
    Q_PROPERTY(int count READ count WRITE setCount NOTIFY countChanged FINAL)

public:
    enum Roles {
        OrderCodeRole = Qt::UserRole + 1,
        ProfileTypeRole,
        ProductNameRole,
        ColorRole,
        CutLengthRole,
        CutCountRole,
        MaterialLengthRole,
        LeftAngleRole,
        RightAngleRole,
        WorkedCountRole
    };

    // 单例模式
    static CutDataModel* getInstance();
    CutDataModel(const CutDataModel&) = delete;
    CutDataModel& operator=(const CutDataModel&) = delete;

    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    QHash<int, QByteArray> roleNames() const override;

    // 新增：CSV文件操作
    Q_INVOKABLE bool saveToCsv();          // 保存数据到save.csv
    Q_INVOKABLE bool readFromCsv();        // 从save.csv读取数据
    Q_INVOKABLE void clearCsvFile();       // 清空save.csv文件


    // 核心：通过索引获取数据项，转换为QVariantMap供QML访问
    Q_INVOKABLE QVariantMap get(int index) const;

    Q_INVOKABLE void incrementWorkedCount(int index);

    Q_INVOKABLE void addData(const cutData &data);

    Q_INVOKABLE void clear();

    int count() const;
    void setCount(int newCount);

signals:
    void countChanged();
    void dataCleared(); // 新增数据已清除信号
    void modelDataUpdated();           // 模型数据更新信号（用于通知QML重置选中状态）

public slots:
    Q_INVOKABLE void setDataList(const QVector<cutData> &dataList);

private:
    explicit CutDataModel(QObject *parent = nullptr);
    ~CutDataModel() override;

    static CutDataModel* m_instance;
    QVector<cutData> m_dataList;
    // mutable QMutex m_mutex; //  mutable允许在const函数中使用
    int m_count;

    QString m_csvFilePath;                 // CSV文件路径

};

#endif // CUTDATAMODEL_H
